package com.cskaoyan.typehandler;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.SneakyThrows;
import org.apache.commons.lang.StringUtils;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedJdbcTypes;
import org.apache.ibatis.type.MappedTypes;
import org.apache.ibatis.type.TypeHandler;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.LinkedList;
import java.util.List;

/**
 * @author zhuqiushi
 * @since 2022/09/07 14:32
 */
@MappedTypes(List.class)
@MappedJdbcTypes(JdbcType.VARCHAR)
public class StringListTypeHandler implements TypeHandler<List<String>> {
    ObjectMapper objectMapper = new ObjectMapper();

    @SneakyThrows
    @Override
    public void setParameter(PreparedStatement preparedStatement, int i, List<String> strings, JdbcType jdbcType) throws SQLException {
        String value = objectMapper.writeValueAsString(strings);
        preparedStatement.setString(i, value);
    }

    @SneakyThrows
    @Override
    public List<String> getResult(ResultSet resultSet, String columnName) throws SQLException {
        //获取sql语句查询的结果
        String string = resultSet.getString(columnName);
        //将String转化为List<string>
        List<String> result = transfer(string);
        return result;
    }

    private List<String> transfer(String string) throws JsonProcessingException {
        LinkedList<String> result = new LinkedList<>();
        if (StringUtils.isEmpty(string)) {
            return result;
        }
        result = objectMapper.readValue(string, LinkedList.class);
        return result;
    }

    @SneakyThrows
    @Override
    public List<String> getResult(ResultSet resultSet, int columnIndex) throws SQLException {
        //获取sql语句查询的结果
        String string = resultSet.getString(columnIndex);
        //将String转化为List<string>
        List<String> result = transfer(string);
        return result;
    }

    @SneakyThrows
    @Override
    public List<String> getResult(CallableStatement callableStatement, int columnIndex) throws SQLException {
        //获取sql语句查询的结果
        String string = callableStatement.getString(columnIndex);
        //将String转化为List<string>
        List<String> result = transfer(string);
        return result;
    }
}
